package com.hxzy.module.auth.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.hxzy.framework.common.constant.AuthConstant;
import com.hxzy.framework.common.exception.ApiException;
import com.hxzy.framework.common.resp.R;
import com.hxzy.framework.common.resp.ResultCode;
import com.hxzy.framework.common.resp.UserDto;
import com.hxzy.module.auth.config.oauth.SecurityUser;
import com.hxzy.module.auth.entity.AdminAccount;
import com.hxzy.module.auth.service.AdminAccountService;
import com.hxzy.module.back.api.backaccount.BackFeignApi;
import com.hxzy.module.back.api.backaccount.resp.BackAccountResp;
import com.hxzy.module.store.api.store.StoreFeignApi;
import com.hxzy.module.store.api.store.resp.StoreAccountResp;
import com.hxzy.module.store.api.store.resp.StoreResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @Author wy
 * @Description 自定义登录认证连接数据库(spring security框架)
 * @Date 2024/1/25 16:36
 * @Version 1.0
 */
@Service
public class UserDetailsImpl implements UserDetailsService {

    @Resource
    private HttpServletRequest request;

    /**
     * 后台总店账户表 ，oauth2.0 client_id=Admin
     */
    @Autowired
    private AdminAccountService  adminAccountService;

    /**
     * 引用远程门店服务
     */
    @Autowired
    private StoreFeignApi  storeFeignApi;

    /**
     * 中台远程服务
     */
    @Autowired
    private BackFeignApi backFeignApi;

    /**
     * springsecurity连接数据库接口
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // oauth2.0密码式访问模式 url地址： http://服务器:端口/oauth/authorize?response_type=password&client_id=admin&scop=all
        //登录账号类型 client_id=[Admin后台管理, Admin_Slave 后台分店管理, back_admin 总端后台]
        String clientId = request.getParameter(AuthConstant.CLIENT_ID);
        String merchantId= request.getHeader(AuthConstant.MERCHANT_ID);

        //查询数据库对应的信息
        UserDto  userDto=null;

        //Admin 总店后台管理
        if (AuthConstant.ADMIN_CLIENT_ID.equals(clientId)) {
            AdminAccount adminAccount= this.adminAccountService.findByUserName(username,Long.parseLong(merchantId));
           //有值
            if (!ObjectUtil.isEmpty(adminAccount)) {
                userDto = new UserDto();
                userDto.setId(adminAccount.getId());
                userDto.setUser_name(adminAccount.getAccount());
                userDto.setPassword(adminAccount.getPassword());
                userDto.setState(adminAccount.getState());
                userDto.setClient_id(clientId);
                userDto.setMerchantId(adminAccount.getMerchantId());
            }
        }else if (AuthConstant.ADMIN_SLAVE_CLIENT_ID.equals(clientId)) {
            //后台分店管理 (feign需要编写拦截器，把merchantId传给远程程序)
            R<StoreAccountResp> storeAccountRespR = this.storeFeignApi.storeAccountFindByAccount(username);
            //远程访问正常的
            StoreAccountResp storeAccountResp = remoteResult(storeAccountRespR);
            //根据账号ID获取账户信息
            R<StoreResp> storeR = this.storeFeignApi.findByStoreId(storeAccountResp.getStoreId());
            StoreResp storeResp = remoteResult(storeR);
            userDto = new UserDto();
            userDto.setId(storeAccountResp.getId());
            userDto.setUser_name(storeAccountResp.getAccount());
            userDto.setPassword(storeAccountResp.getPassword());
            userDto.setState(storeResp.getState());
            userDto.setClient_id(clientId);
            userDto.setStoreId(storeResp.getStoreId());
            userDto.setMerchantId(storeAccountResp.getMerchantId());

        }else if (AuthConstant.BACK_ADMIN_CLIENT_ID.equals(clientId)){
            //总端后台client_id
            R<BackAccountResp> accountRespR = this.backFeignApi.findByAccount(username);
            BackAccountResp backAccount = this.remoteResult(accountRespR);
            userDto = new UserDto();
            userDto.setId(backAccount.getId());
            userDto.setUser_name(backAccount.getAccount());
            userDto.setPassword(backAccount.getPassword());
            userDto.setState(backAccount.getState());
            userDto.setClient_id(clientId);

        }else{
            throw new ApiException(500, "未知异常");
        }

        //判断userDto是否为null
        if (null == userDto) {
            throw new UsernameNotFoundException("帐号或密码错误");
        }

        //自定义springsecurity需要的返回接口实现类 UserDetails
        SecurityUser  securityUser=new SecurityUser(userDto);
        if (!securityUser.isEnabled()) {
            throw new DisabledException("该账户已被禁用，请联系管理员");
        }
        return securityUser;
    }

    /**
     * 远程数据读取
     * @param r
     * @param <T>
     * @return
     */
    private <T> T remoteResult(R<T> r){
        if(ResultCode.SUCCESS.getCode()==r.getCode()){
            return r.getData();
        }
        throw new ApiException(r.getCode(),r.getMsg());
    }


}
